package com.ruoyi.common.config.websockert;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public class WsTest {

	// 1. 日志器
	private static final Logger LOG = Logger.getLogger(WsTest.class.getName());

	public static void main(String[] args) throws Exception {
		// 2. 目标地址
//		String url = "ws://localhost:8087/wss";   // 本地
		String url = "ws://localhost:8087/ws/websocket";   // 以浏览器实际为准
		// String url = "wss://ceshi2.dishait.cn/wss";   // 线上

		HttpClient client = HttpClient.newHttpClient();
		CountDownLatch latch = new CountDownLatch(1);

		LOG.info(">>> 开始连接：" + url);

		client.newWebSocketBuilder()
			.buildAsync(URI.create(url), new WebSocket.Listener() {

				private void log(String msg) {
					LOG.info("[" + LocalTime.now()
						.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))
						+ "] " + msg);
				}

				@Override
				public void onOpen(WebSocket webSocket) {
					log("✅ 连接成功");
					String ping = "{\"type\":\"text\",\"data\":\"Hello from Java\"}";
					log(">>> 发送：" + ping);
					webSocket.sendText(ping, true);
				}

				@Override
				public CompletionStage<?> onText(WebSocket webSocket,
				                                 CharSequence data,
				                                 boolean last) {
					log("<<< 收到消息：" + data);
					latch.countDown();
					return null;
				}

				@Override
				public void onError(WebSocket webSocket, Throwable error) {
					log("❌ 发生错误：" + error.getMessage());
					latch.countDown();
				}

				@Override
				public CompletionStage<?> onClose(WebSocket webSocket,
				                                  int statusCode,
				                                  String reason) {
					log("🔌 连接关闭：" + statusCode + " " + reason);
					latch.countDown();
					return null;
				}
			});

		// 3. 最长等待 10 秒
		boolean ok = latch.await(10, TimeUnit.SECONDS);
		if (!ok) {
			LOG.warning("⏰ 等待超时，10 秒内未收到任何消息");
		}
		LOG.info(">>> 测试结束");
	}
}
